package com.liang.subject.application.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.liang.subject.application.convert.SubjectLikedDTOConverter;
import com.liang.subject.application.dto.SubjectInfoDTO;
import com.liang.subject.application.dto.SubjectLikedDTO;
import com.liang.subject.common.entity.PageDTO;
import com.liang.subject.common.entity.Result;
import com.liang.subject.common.util.LoginUtil;
import com.liang.subject.domain.entity.SubjectInfoBO;
import com.liang.subject.domain.entity.SubjectLikedBO;
import com.liang.subject.domain.service.SubjectLikedDomainService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/subjectLiked")
@RequiredArgsConstructor
public class SubjectLikedController {

    private final SubjectLikedDomainService subjectLikedDomainService;

    /**
     * 新增题目点赞信息
     */
    @PostMapping("/save")
    public Result<Void> save(@RequestBody SubjectLikedDTO subjectLikedDTO) {
        try {
            log.info("SubjectLikedController.save.dto:{}", JSON.toJSONString(subjectLikedDTO));
            Preconditions.checkNotNull(subjectLikedDTO.getSubjectId(), "题目ID不能为空");
            Preconditions.checkNotNull(subjectLikedDTO.getStatus(), "题目状态不能为空");
            subjectLikedDTO.setLikeUserId(LoginUtil.getLoginId());
            Preconditions.checkArgument(StrUtil.isNotBlank(subjectLikedDTO.getLikeUserId()), "点赞用户不能为空");
            SubjectLikedBO subjectLikedBO = SubjectLikedDTOConverter.INSTANCE.convertDTO2BO(subjectLikedDTO);
            subjectLikedDomainService.save(subjectLikedBO);
            return Result.ok();
        } catch (Exception e) {
            log.error("SubjectLikedController.save.error", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 我的点赞
     */
    @PostMapping("/getSubjectLikedPage")
    public Result<PageDTO<SubjectLikedBO>> getSubjectLikedPage(@RequestBody SubjectLikedDTO subjectLikedDTO) {
        log.info("SubjectLikedController.getSubjectLikedPage.dto:{}", JSON.toJSONString(subjectLikedDTO));
        subjectLikedDTO.setLikeUserId(LoginUtil.getLoginId());
        Preconditions.checkArgument(StrUtil.isNotBlank(subjectLikedDTO.getLikeUserId()), "点赞用户不能为空");
        SubjectLikedBO subjectLikedBO = SubjectLikedDTOConverter.INSTANCE.convertDTO2BO(subjectLikedDTO);
        PageDTO<SubjectLikedBO> res = subjectLikedDomainService.getSubjectLikedPage(subjectLikedBO);
        return Result.ok(res);
    }
}
